var go = document.getElementById("go")
var main = document.getElementById("main")
var speed = 1,
    timer,
    nums = 0,
    flag = true
var colorArr = ["yellow", "red", "blue", "pink"]
//点击开始游戏
function clickStart() {
    go.addEventListener("click", function () {
        go.style.display = "none"
        move()
    })
}

clickStart();


//移动函数  判断游戏是否结束
function move() {
    clearInterval(timer)
    timer = setInterval(function () {
        var step = parseInt(main.offsetTop) + speed
        main.style.top = step + "px"
        if (parseInt(main.offsetTop) >= 0) {
            main.style.top = "-150px"
            cDiv()
        }
        var len = main.childNodes.length
        if (len >= 6) {
            for (var i = 0; i < 4; i++) {
                if (main.childNodes[len - 1].childNodes[i].classList.contains("i")) {
                    alert("游戏结束 得分" + nums)
                    flag = false
                    clearInterval(timer)
                }
            }
            main.removeChild(main.childNodes[len - 1])
        }
    }, 20)
    bindEvent()
}

//创建行和列 方块
function cDiv() {
    var oDiv = document.createElement("div")
    oDiv.setAttribute("class", "row")
    var index = Math.floor(Math.random() * 4)
    for (var i = 0; i < 4; i++) {
        var iDiv = document.createElement("div")
        oDiv.appendChild(iDiv)
    }
    if (main.childNodes.length === 0) {
        main.appendChild(oDiv)
    } else {
        main.insertBefore(oDiv, main.childNodes[0])
    }
    var clickDiv = main.childNodes[0].childNodes[index]
    clickDiv.setAttribute("class", "i")
    clickDiv.style.backgroundColor = colorArr[index]
}

//游戏开始 点击方块 判断游戏是否结束
function bindEvent() {
    main.addEventListener("click", function (e) {
        if (flag) {
            var tar = e.target
            if (tar.className === "i") {
                tar.style.backgroundColor = "#bbb"
                tar.classList.remove("i")
                nums++
            } else {
                alert("游戏结束 得分" + nums)
                flag = false
                clearInterval(timer)
            }
            if (nums % 10 === 0) {
                speed++
            }
        } 
    })
}